package org.jsping.service.impl;

import java.sql.SQLException;

import org.jsping.dao.impl.CollectionDaoImpl;
import org.jsping.service.ICollectionSerice;

public class CollectionServiceImpl implements ICollectionSerice{
	CollectionDaoImpl cImpl = new CollectionDaoImpl();

	/*添加*/
	@Override
	public int addRecord(int uid, int mid) throws SQLException {
		int result = 0;
		//判断  用户是否存在
		if(this.isExists(uid)) {
			String rec = getRecord(uid);	//获取record
			String [] words = rec.split(",");//拆分 
			
			//用户存在,mid不存在,就添加,否则就不添加
			if(hasId(mid, words)==-1) {
				rec += mid;    //重新拼接
				result = this.updateRecord(mid,rec);
			}
		}else {
			result = cImpl.addRecord(uid, mid);
		}
		return result;
	}

	/*判断mid*/
	public int hasId(int mid,String []arr) {
		for (int i = 0; i < arr.length; i++) {
			if(arr[i].equals(String.valueOf(mid))) {
				return i;
			}
		}
		return -1;
	}

	/*更新*/
	@Override
	public int updateRecord(int uid, String record) throws SQLException {
		int result = 0;
		if(isExists(uid)){
			result = cImpl.updateRecord(uid, record);
		}
		return result;
	}

	/*获取records*/
	@Override
	public String getRecord(int uid) throws SQLException {
		return cImpl.getRecord(uid);
	}

	/*用户是否存在*/
	@Override
	public boolean isExists(int uid) throws SQLException {
		boolean flag = false;
		if(cImpl.isExists(uid)!=null) {
			flag = true;
		}
		return flag;
	}

}
